package com.icim.csot.importer.job;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.icim.core.pojo.FtpConfigure;
import com.icim.core.service.IFtpService;
import com.icim.csot.importer.service.IRetCusPrdInService;
import com.icim.csot.importer.service.impl.RetCusSoServiceImpl;
import com.icim.csot.importer.xmlentity.CsotMtrlInXmlEntity;
import com.icim.csot.importer.xmlentity.CsotSalesOrderXmlEntity;
import com.icim.entity.Ret_cus_so;
import com.icim.util.Dom4jUtil;
import com.icim.util.FileUtil;
import com.icim.util.GzCompressUtil;
import com.icim.util.XmlConvertUtil;

public class CsotImportJob {
    private static final String TRX_CSOT_SALESORDER = "BA_WORKORDER";
    private static final String TRX_CSOT_MTRL_IN = "CSOTOUTSOURCING";
    private static final Logger logger = LoggerFactory.getLogger(CsotImportJob.class);
    private IFtpService ftpService;

    private RetCusSoServiceImpl retCusSoSerice;

    private IRetCusPrdInService retCusPrdInService;

    public void setFtpService(IFtpService ftpService) {
        this.ftpService = ftpService;
    }

    public void setRetCusPrdInService(IRetCusPrdInService retCusPrdInService) {
        this.retCusPrdInService = retCusPrdInService;
    }

    public void setRetCusSoSerice(RetCusSoServiceImpl retCusSoSerice) {
        this.retCusSoSerice = retCusSoSerice;
    }

    public void subMainProc() {

        FtpConfigure ftpConfigure = ftpService.getFtpConfigure();
        String localTempPath = ftpConfigure.getLocalTemporaryPath();
        String localGzPath = ftpConfigure.getLocalGzPath();
        String localPath = localTempPath;

        logger.info("csot importer job starting ......");

        String gzFileName = null;
        try {
            // 连接FTP
            ftpService.connect();

            // 获取文件列表
            List<String> fileNameList = ftpService.listFiles(FileUtil.GZ);

            // 遍历GZ文件
            for (String fileName : fileNameList) {

                gzFileName = fileName;
                logger.info("find file [{}]", fileName);

                // 下载GZ文件到本地
                ftpService.downLoadFile(fileName);
                String localGzFileName = localPath + "/" + fileName;

                try {
                    File localGzFile = new File(localGzFileName);

                    // 解压
                    GzCompressUtil.decompress(localGzFile);

                    // 获取解压后的XML
                    // 列出XML文件时，不需要关注扩展名
                    File[] xmlFiles = FileUtil.listFiles(localPath);

                    for (File xmlFile : xmlFiles) {

                        String trxId = Dom4jUtil.getTrxId(xmlFile);
                        if (StringUtils.equalsIgnoreCase(TRX_CSOT_SALESORDER,trxId)) {
                            importSalesOrderProc(xmlFile);
                        } else if (StringUtils.equalsIgnoreCase(TRX_CSOT_MTRL_IN,trxId)) {
                            importOutSource(xmlFile);
                        }else{
                            logger.error("不合法的trx_name:" + trxId);
                            throw new RuntimeException("不合法的trx_name:" + trxId);
                        }

                        // // 删除本地临时XML文件
                        // FileUtil.deleteFile(xmlFile);
                        GzCompressUtil.compress(xmlFile);
                    }

                    // 将GZ档移到本地备份目录

                    FileUtil.removeFile(fileName, localTempPath, localGzPath);

                    // 将压缩文件从原始路径 移动到OK或者NG路径
                    ftpService.removeFiles(localGzFile.getName(), true);

                } catch (Exception ex) {
                    logger.error(ex.toString());
                    if (!StringUtils.isEmpty(gzFileName)) {
                        ftpService.removeFiles(gzFileName, false);
                    }
                    // TODO
                    sendAlarm();

                } finally {

                    storeLocalGzFile(localTempPath, localGzPath, localPath);

                }

            }

        } catch (Exception e) {
            sendAlarm();
            logger.error(e.toString());
        } finally {

            // 断开连接
            try {
                // FileUtil.deleteAllFiles(localPath, FileUtil.GZ);
                ftpService.disconnectFtp();
            } catch (IOException e) {
                logger.error(e.toString());
            }
        }

        storeLocalGzFile(localTempPath, localGzPath, localPath);
    }

    private void storeLocalGzFile(String localTempPath, String localGzPath, String localPath) {
        File[] xmlFiles = FileUtil.listFiles(localPath);
        for (File xmlFile : xmlFiles) {
            if (!xmlFile.getName().endsWith(".gz")) {
                try {
                    GzCompressUtil.compress(xmlFile);
                    FileUtil.removeFile(xmlFile.getName() + ".gz", localTempPath, localGzPath);
                } catch (Exception e) {
                    logger.error(e.toString());
                }
            }else{
            	FileUtil.removeFile(xmlFile.getName(), localTempPath, localGzPath);
            }
            

        }
    }

    private void importOutSource(File xmlFile) throws DocumentException {
        // 解析XML，将xml转换为对象实体
        CsotMtrlInXmlEntity mtrlInXmlEntity = (CsotMtrlInXmlEntity) XmlConvertUtil.file2Object(xmlFile,
                CsotMtrlInXmlEntity.class);

        retCusPrdInService.save(mtrlInXmlEntity);
    }

    private void importSalesOrderProc(File xmlFile) {
        // 解析XML，将xml转换为对象实体
        CsotSalesOrderXmlEntity csotOrder = (CsotSalesOrderXmlEntity) XmlConvertUtil.file2Object(xmlFile,
                CsotSalesOrderXmlEntity.class);

        // 将XML对象实体转化为数据库实体
        Ret_cus_so retCusSo = new Ret_cus_so();
        retCusSo.CostSalesOrderXml2Entity(csotOrder);

        // 写入DB
        retCusSoSerice.save(retCusSo);
    }

    private void sendAlarm() {
        // TODO Auto-generated method stub

    }

}
